unit miscfunc;
(*
  srcstr
    miscfunc.pas - program functions
    (c)2006-2012 Matthew Hipkin <http://www.matthewhipkin.co.uk>
*)
{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils{$IFDEF MSWINDOWS}, Windows{$ENDIF}, dateutils, xmlparser,
  md5;

type
  TskProject = record
    id: integer;
    title: string;
    description: string;
    localDir: string;
  end;

function getOS: String;
{$IFDEF MSWINDOWS}function getWinVer: String; {$ENDIF}
function cacheXML(content: String; dir: String): String;
function skFileSize(fname: String): integer;
function checkError(xml: String): Integer;
function md5checksum(fileName: String): String;

implementation

function getOS: String;
begin
  {$IFDEF Windows}
   Result := getWinVer;
  {$ENDIF}
  {$ifdef Linux}
   Result := 'Linux';
  {$endif}
  {$ifdef FreeBSD}
   Result := 'FreeBSD';
  {$endif}
  {$ifdef Darwin}
   Result := 'Mac OSX';
  {$endif}
end;

{$IFDEF MSWINDOWS}
function getWinVer: String;
var
  VerInfo: TOSVersioninfo;
begin
  VerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
  GetVersionEx(VerInfo);
  Result := 'Windows '+IntToStr(VerInfo.dwMajorVersion) + '.' + IntToStr(VerInfo.dwMinorVersion)
end;
{$ENDIF}

function cacheXML(content: String; dir: String): String;
var
  t: String;
  i: integer;
  f: TextFile;
begin
  Randomize;
  i := Random(1000)+1;
  t := IntToStr(DateTimeToUnix(Now));
  t := t + IntToStr(i);
  if not DirectoryExists(dir + 'cache') then mkdir(dir + 'cache');
  AssignFile(f,dir + 'cache' + PathDelim + t + '.xml');
  Rewrite(f);
  Write(f,content);
  CloseFile(f);
  Result := dir + 'cache' + PathDelim + t + '.xml';
end;

function skFileSize(fname: String): integer;
var
  F: file of byte;
begin
  Result := 0;
  if FileExists(fname) then
  begin
    AssignFile(F,fname);
    Reset(F);
    Result := FileSize(F);
    CloseFile(F);
  end;
end;

function checkError(xml: String): Integer;
var
  Parser: TXMLParser;
begin
  Result := 0;
  Parser := TXMLParser.Create(xml);
  While Parser.Next do
  begin
    if (Parser.TagType = ttBeginTag) and (Parser.Name = 'errorCode') then
    begin
      Result := StrToInt(Parser.ContentCode);
    end;
  end;
  Parser.Free;
end;

function md5checksum(fileName: String): String;
var
  m: TMD5Digest;
begin
  m := MD5File(fileName);
  Result := MD5Print(m);
end;

end.

